package main

import (
	"cloud-entropy-storage-system/server/internal/config"
	"cloud-entropy-storage-system/server/internal/router"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"runtime/pprof"
	"syscall"

	"github.com/zeromicro/go-zero/core/conf"
)

var (
	configFile = flag.String("f", "etc/config.yaml", "the config file")
	cfg        config.Config
)

func main() {
	flag.Parse()
	conf.MustLoad(*configFile, &cfg)
	s := router.NewServer(cfg)

	go func() {
		if err := s.Engine.Run(fmt.Sprintf("%s:%d", cfg.HttpServer.Host, cfg.HttpServer.Port)); err != nil {
			s.Log.Error(err.Error())
			os.Exit(1)
		}
	}()
	go writePProf()

	shutDown(s)
}

func writePProf() {
	cpufile, err := os.Create("cpu.pprof")
	if err != nil {
		panic(err)
	}
	err = pprof.StartCPUProfile(cpufile)
	if err != nil {
		panic(err)
	}
	defer cpufile.Close()
	defer pprof.StopCPUProfile()

}

func shutDown(server *router.Server) {
	signals := make(chan os.Signal)
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
	sig := <-signals

	server.Close()

	switch sig {
	case syscall.SIGINT:
		os.Exit(int(syscall.SIGINT))
	case syscall.SIGTERM:
		os.Exit(int(syscall.SIGTERM))
	}
}
